package org.example;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;

public class Task4Driver1 {
    public static class Task4Mapper1 extends Mapper<Object,Text,Text,Text>{
        @Override
        public void map(Object key,Text value,Context context) throws IOException, InterruptedException{
            String[] parts=value.toString().split(",");
            if(parts.length>=5) {
                Text weekNum=new Text(parts[4]);
                String tmpDatas=parts[0]+","+parts[1]+","+parts[2]+","+parts[3];
                Text datas=new Text(tmpDatas);
                context.write(weekNum,datas);
            }
        }
    }

    public static class Task4Reducer1 extends Reducer<Text,Text,Text,Text>{
        @Override
        public void reduce(Text key,Iterable<Text> values,Context context) throws IOException,InterruptedException{
            int count=0;
            double avgBankRate=0.0;
            double avgBaoRate=0.0;
            long avgPurchaseAmt=0;
            long avgRedeemAmt=0;
            for(Text val:values){
                String[] line=val.toString().split(",");
                avgBankRate+=Double.parseDouble(line[0]);
                avgBaoRate+=Double.parseDouble(line[1]);
                avgPurchaseAmt+=Integer.parseInt(line[2]);
                avgRedeemAmt+=Integer.parseInt(line[3]);
                count++;
            }
            avgBankRate=avgBankRate/count;
            avgBaoRate=avgBaoRate/count;
            avgPurchaseAmt=Math.round((float) avgPurchaseAmt /count);
            avgRedeemAmt=Math.round((float) avgRedeemAmt /count);
            String result = String.format("%f,%f,%d,%d", avgBankRate, avgBaoRate, avgPurchaseAmt, avgRedeemAmt);
            Text tmpResult=new Text(result);
            context.write(key,tmpResult);
        }
    }
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "task4 average week datas");

        job.setJarByClass(Task4Driver1.class);
        job.setMapperClass(Task4Driver1.Task4Mapper1.class);
        job.setReducerClass(Task4Driver1.Task4Reducer1.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setNumReduceTasks(1);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
